# -*- coding: utf-8 -*-
import aliLink,mqttd,rpi,oss2,cv2,os,time,json,multiprocessing,sys,random,json
import aliyunsdkiotclient.AliyunIotMqttClient as iot 
import tkinter as tk
import tkinter.filedialog as filedialog

# 配置OSS access_key_id和access_key_secret
access_key_id = '填入你的access_key_id'
access_key_secret = '填入你的access_key_secret'
auth = oss2.Auth(access_key_id, access_key_secret)

# 配置OSS endpoint和bucket_name
endpoint = '填入你的OSS endpoint 例如：上海的OSS库 oss-cn-shanghai.aliyuncs.com'
bucket_name = '填入你的BUCKET名称'
bucket = oss2.Bucket(auth, endpoint, bucket_name)

options = {
    'productKey':'填入你的设备productKey',
    'deviceName':'填入你的设备deviceName',
    'deviceSecret':'填入你的设备deviceSecret',
    'port':1883,
    'host':'填入你的物联网平台域名 例如：上海的 iot-as-mqtt.cn-shanghai.aliyuncs.com',##物联网平台域名
    'bucket_name':'填入你的BUCKET名称'
}
host = options['productKey'] + '.' + options['host']

#连接回调（与阿里云建立链接后的回调函数）
def on_connect(client, userdata, flags, rc):
    pass

#选择文件上传到OSS并且将URL与其他信息上报物联网平台
def report_to_aliyun():

	#使用IoT Python SDK创建一个阿里云IoT MQTT客户端，需要提供设备的ProductKey，DeviceName和DeviceSecret信息，并且设置安全模式为3（使用TLS加密连接）。
    client = iot.getAliyunIotMqttClient(options['productKey'], options['deviceName'], options['deviceSecret'], secure_mode=3)
	#设置连接成功后的回调函数，当客户端成功连接到MQTT服务器时，将自动调用此函数。
    client.on_connect = on_connect
	#使用给定的主机地址，端口和保持连接时间连接到MQTT服务器。
    client.connect(host=host, port=options['port'], keepalive=60)
	#定义要发布消息的主题，主题由设备的ProductKey，DeviceName和事件属性名称组成。
    topic = '/sys/'+options['productKey']+'/'+options['deviceName']+'/thing/event/property/post'
    
    # 信息获取上报
    CPU_temp = random.randint(40, 80) # 温度   ℃
    CPU_usage = random.randint(20, 100)        # 占用率 %
    
    # 创建图形界面
    root = tk.Tk()
    root.withdraw()

    # 通过文件资源管理器选择待上传的文件
    file_path = filedialog.askopenfilename()
    if not file_path:
        print('未选择任何文件')
        exit()
    print(file_path)

    # 设置上传到OSS的文件名，可包含路径
    object_name = 'test01/' + file_path.split('/')[-1]

    # 检查文件后缀，如果是jpg则使用URL_name_pic001，如果是mp4则使用URL_video_001
    if file_path.endswith('.jpg'):
        URL_name_pic001 = 'https://' + options['bucket_name'] + '.oss-cn-shanghai.aliyuncs.com/' + object_name
        URL_video_001 = 'None'

    elif file_path.endswith('.mp4'):
        URL_name_pic001 = 'None'
        URL_video_001 = 'https://' + options['bucket_name'] + '.oss-cn-shanghai.aliyuncs.com/' + object_name
    else:
        URL_name_pic001 = 'None'
        URL_video_001 = 'None'
        print('不支持的文件格式')
        exit()

    # 上传文件
    bucket.put_object_from_file(object_name, file_path)   
         
    # 构建与云端模型一致的消息结构    
    if URL_name_pic001 == 'None' and URL_video_001 == 'None':
     	payload_json = {
									"params" : { 
									'cpu_temperature':CPU_temp, 
									'cpu_usage':CPU_usage, 
									}, 
							'method': "thing.event.property.post" 
              }
					
    elif  URL_name_pic001  ==  'None':
      payload_json  = {
											"params" : { 
											'cpu_temperature':CPU_temp, 
											'cpu_usage':CPU_usage, 
											'URL_video_001':URL_video_001
											}, 
									'method': "thing.event.property.post" 
              }
    elif  URL_video_001 ==  'None':
      payload_json  = {
				          "params" : {
				              'cpu_temperature':CPU_temp,
				              'cpu_usage':CPU_usage,
				              'URL_pic001':URL_name_pic001
				          },
				     'method': "thing.event.property.post"
              }
    else:
      payload_json  = {
				          "params" : {
				              'cpu_temperature':CPU_temp,
				              'cpu_usage':CPU_usage,
				              'URL_pic001':URL_name_pic001,
				              'URL_video_001':URL_video_001
				          },
				     'method': "thing.event.property.post"
				  }

		#输出上报内容        
    print(payload_json)
    
    client.publish(topic, payload=str(payload_json))

def main():
	#URL_name_pic001, URL_video_001 = upload_file_to_oss() #使用两个变量分别接收URL_name_pic001和URL_video_001的返回值
	#report_to_aliyun(URL_name_pic001, URL_video_001) #将两个变量作为参数传递给report_to_aliyun函数
	report_to_aliyun()  
if __name__ == '__main__':

	main()
	
print('Done')
